package com.zhoumy.interview.study.thread;

/**
 * MultiThreadSingletonDemo（多线程的 单例模式）
 *
 * @author: zhoumy
 * @create: 2024年6月3日19:09:38
 */
public class DCLSingletonDemo {

    private static volatile DCLSingletonDemo instance = null;

    private DCLSingletonDemo() {
        System.out.println(Thread.currentThread().getName() + "\t 我是构造方法SingletonDemo");
    }

    // DCL(Double Check Lock 双端检测锁机制)
    public static DCLSingletonDemo getInstance() {
        if (instance == null) {
            synchronized (DCLSingletonDemo.class) {  //双端检测锁机制: 加锁前后都做判空检测
                if (instance == null) {
                    instance = new DCLSingletonDemo();
                }
            }
        }
        return instance;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10000000; i++) {
            new Thread(() -> {
                DCLSingletonDemo.getInstance();
            }, String.valueOf(i)).start();
        }
    }
}

